package net.xinqushi.design.templateMethod.core;

import net.xinqushi.design.templateMethod.util.NumberUtils;

import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SimpleSocketMessageSender extends SocketMessageSender {

	protected Socket socket=null;

	public SimpleSocketMessageSender(String host, int port, String username,
			String password) {
		super(host, port, username, password);
	}

	@Override
	protected String messageSent(String message) throws Exception {
		socket.setSoTimeout(readTimeout);
		ByteArrayOutputStream write_buff=new ByteArrayOutputStream();
		byte[] bytes=message.getBytes();
		write_buff.write(NumberUtils.convertIntegerToByteArray(bytes.length));
		write_buff.write(bytes);
		write_buff.writeTo(socket.getOutputStream());
		write_buff.close();
		byte[] read_buff=new byte[readBufferSize];
		String returnVal="402";
		int readBytes=0;
		while(true){
			if((readBytes=socket.getInputStream().read(read_buff))>0){
				break;
			}
		}
		write_buff=new ByteArrayOutputStream();
		write_buff.write(read_buff, 0, readBytes);
		returnVal=write_buff.toString();
		write_buff.close();
		return returnVal;
	}


	@Override
	protected void onPreSent() throws Exception {
		try{
			if(socket==null){
				socket=new Socket();
				socket.connect(new InetSocketAddress(host,port), waitTimeout);
			}
		}catch(Exception e){
			socket=null;
			socket=new Socket();
			socket.connect(new InetSocketAddress(host,port), waitTimeout);
		}
	}

	@Override
	protected void onPostSent() throws Exception {
		if(socket!=null&&!socket.isClosed()){
			socket.close();
			socket=null;
		}
	}

}
